﻿using static CyberU;
using static CyberU.UI;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Unity.VisualScripting;
using UnityEngine.Serialization;
using Cache = UnityEngine.Cache;

public class MusicPlayer: MonoBehaviour
{
    public string currentAlbum;
    public List<AlbumInfo> albums = new List<AlbumInfo>();
    public List<SongInfo> songs = new List<SongInfo>();
    public SongsSelector songsSelector;
    public AlbumsSelector albumsSelector;
    public class AlbumsSelector : LoopScrollSelector<AlbumItem>
    {
        void Start()
        {
            // Delog("is creating...");
            base.Start();
            totalShowNum = 3;
            direction = "horizontal";
        }
        public override void AfterNewItemSelected()
        {
            // Delog($"AfterNewItemSelected {{lastIndex}} {index}");
            // Delog(items[newIndex].filePath);
            GetComponentInParent<MusicPlayer>().RefreshSongs();
        }
        public override void AfterRepeatSelected()
        {
            // Delog(items[index].filePath);
            // Delog($"afterRepeatSelected {index}");
        }
    };
    public class SongsSelector : LoopScrollSelector<MusicItem>
    {
        void Start()
        {
            // Delog("is creating...");
            base.Start();
            totalShowNum = 5;
            // layoutGroup.childAlignment = TextAnchor.MiddleLeft;
        }

        public int lastPlayedDataIndex;
        public override void AfterNewItemSelected()
        {
            // Delog($"AfterNewItemSelected {lastPlayedDataIndex} {dataIndex}");
            // Delog(items[newIndex].filePath);
            items[lastPlayedDataIndex].Pause();
            items[dataIndex].Play();
            lastPlayedDataIndex=dataIndex;
        }
        public override void AfterRepeatSelected()
        {
            // Delog(items[index].filePath);
            // Delog($"afterRepeatSelected {lastDataIndex} {dataIndex}");
            items[dataIndex].ToggleAudioPlaying();
            lastPlayedDataIndex=dataIndex;
        }
    };


    public int currentIndex
    {
        get { return songsSelector.dataIndex; }
        set { switchIndex(value); }
    }
    public void switchIndex(int index)
    {
        songsSelector.switchIndex(index);
    }

    public SongInfo currentSong
    {
        get
        {
            if (songs != null && currentIndex >= 0 && currentIndex < songs.Count)
            {
                return songs[currentIndex];
            }

            return null;
        }
        set { }
    }


    public void Start()
    {
        GameObject playList=GetGameObject("Songs",parent:gameObject);
        GameObject albumList=GetGameObject("Albums",parent:gameObject);
        songsSelector = AddComponent<SongsSelector>(playList);
        albumsSelector = AddComponent<AlbumsSelector>(albumList);
        // print($"start musicPlayer {scrollSelectorGameObject==null} | {scrollSelector==null} | ");
        RefreshAlbums();
    }


    public void RefreshAlbums()
    {
        SendCode("music_repositories=MusicRepository()");
        JArray paths = SendCode("[_.path for _ in music_repositories.albums]") as JArray;
        JArray names = SendCode("[_.name for _ in music_repositories.albums]") as JArray;
        for (int i = 0; i < paths.Count && i < names.Count; i++)
        {
            string path = paths[i].ToString();
            string name = names[i].ToString();
            AlbumInfo albumInfo = new AlbumInfo
            {
                name = name,
                // album = currentAlbum,
                // artist = "",
                title = name,
                path = path
            };
            AlbumItem albumItem = AlbumItem.CreateAlbumItem(parent: this, index: i, path: path, loop: true);
            albumInfo.albumItem = albumItem;
            albumsSelector.Add(name, albumItem);
            albums.Add(albumInfo);
        }
        AllMiddleCenter(albumsSelector.layoutGroup);

        RefreshSongs();
    }
    public void RefreshSongs()
    {
        foreach (var song in songs)
        {
            DestroyGameObject(song.musicItem);
        }
        songs.Clear();
        // ClearChildren(songsSelector);
        
        JArray paths = SendCode("music_repositories.get_current_play_paths()") as JArray;
        JArray names = SendCode("[_['name'] for _ in music_repositories.songs]") as JArray;
        for (int i = 0; i < paths.Count && i < names.Count; i++)
        {
            string path = paths[i].ToString();
            string name = names[i].ToString();
            SongInfo songInfo = new SongInfo
            {
                name = name,
                // album = currentAlbum,
                // artist = "",
                title = name,
                path = path
            };
            // print(scrollSelector);
            MusicItem musicItem = MusicItem.CreateMusicItem(parent: this, index: i, path: path, loop: true);
            songInfo.musicItem = musicItem;
            // MusicItem musicItem = Instantiate(MusicItem.musicItemPrefab, scrollSelector.transform).AddComponent<MusicItem>();
            songsSelector.Add(name, musicItem);
            // musicItem.item = scrollSelectorItem;
            songs.Add(songInfo);
        }
        AllMiddleCenter(songsSelector.layoutGroup);
    }

}